/**
 * Copyright (C) cedarsoft GmbH.
 *
 * Licensed under the GNU General Public License version 3 (the "License")
 * with Classpath Exception; you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *         http://www.cedarsoft.org/gpl3ce
 *         (GPL 3 with Classpath Exception)
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 only, as
 * published by the Free Software Foundation. cedarsoft GmbH designates this
 * particular file as subject to the "Classpath" exception as provided
 * by cedarsoft GmbH in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 3 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 3 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
 * or visit www.cedarsoft.com if you need additional information or
 * have any questions.
 */

package com.exadel.google;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.*;


import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class K7Controller implements Registrator {
    private final String EMAIL = "123@gmail.com";
    final public static String REGISTRATION_PAGE = "http://voicemail.k7.net/signup/";
    final public static String LOGIN_PAGE = "http://voicemail.k7.net/";
    final public static String REGISTRATION_CODE = "1234";

    private String currentPhoneNumber;

    private WebClient webClient;
    private HtmlPage registrationPage;

    public K7Controller() {
        webClient = new WebClient();
        try {
            registrationPage = webClient.getPage(REGISTRATION_PAGE);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public URL getCaptcha() {
        URL result = null;
        try {
            registrationPage = webClient.getPage(REGISTRATION_PAGE);
            return new URL(((HtmlImage) (registrationPage.getByXPath("/*//*[@id=\"recaptcha_image\"]/img").get(0))).getSrcAttribute());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public void fillFields() {
        try {
            HtmlTextInput input = (HtmlTextInput) registrationPage.getByXPath("/html/body/form/table[1]/tbody/tr[1]/td[2]/input").get(0);
            input.setValueAttribute(EMAIL);
            input = (HtmlTextInput) registrationPage.getByXPath("/html/body/form/table[1]/tbody/tr[2]/td[2]/input").get(0);
            input.setValueAttribute(EMAIL);
            System.out.println(registrationPage.asText());
            HtmlPasswordInput passwordInput = (HtmlPasswordInput) registrationPage.getByXPath("/html/body/form/table[1]/tbody/tr[3]/td[2]/input").get(0);
            passwordInput.setValueAttribute(REGISTRATION_CODE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public URL getLastAudioFileUrl() throws MalformedURLException {
        HtmlPage workPage = null;
        try {
            workPage = webClient.getPage(LOGIN_PAGE);
            Thread.sleep(1000);
            workPage = signIn(workPage);
            while (workPage.getByXPath("/html/body/table[5]/tbody/tr[2]/td[5]/a").size() == 0) {
                Thread.sleep(5000);
                workPage = signIn(workPage);
            }
            System.out.println(workPage.asText());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String url = ((HtmlElement) workPage.getByXPath("/html/body/table[5]/tbody/tr[2]/td[5]/a").get(0)).getAttribute("href");
        System.out.println(url);

        return new URL(url);
    }

    public boolean createAccount(String captcha) {
        try {
            HtmlTextInput input = (HtmlTextInput) registrationPage.getByXPath("/*//*[@id=\"recaptcha_response_field\"]").get(0);
            input.setValueAttribute(captcha);
            HtmlSubmitInput submit = (HtmlSubmitInput) registrationPage.getByXPath("/html/body/form/div/input[1]").get(0);
            registrationPage = submit.click();

            if (registrationPage.asText().contains("Invalid verification codes.")) {
                return false;
            }
            currentPhoneNumber = registrationPage.getByXPath("/html/body/table[2]/tbody/tr[3]/td/table/tbody/tr[1]/td/text()").get(0).toString();
            parseNumber();
            System.out.println(currentPhoneNumber);
            addPhoneToBook();
            registrationPage = webClient.getPage(REGISTRATION_PAGE);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public URL refreshCaptcha() {
        URL result = null;
        try {
            registrationPage = webClient.getPage(REGISTRATION_PAGE);
            ((HtmlElement) registrationPage.getByXPath("//*[@id=\"recaptcha_reload_btn\"]").get(0)).click();
            return new URL(((HtmlImage) (registrationPage.getByXPath("/*//*[@id=\"recaptcha_image\"]/img").get(0))).getSrcAttribute());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private HtmlPage signIn(HtmlPage page) throws IOException {
        HtmlInput input = (HtmlInput) page.getByXPath("/html/body/table[2]/tbody/tr[3]/td/table/tbody/tr[3]/td[2]/input").get(0);
        input.setValueAttribute(currentPhoneNumber);
        HtmlPasswordInput passwordInput = (HtmlPasswordInput) page.getByXPath("/html/body/table[2]/tbody/tr[3]/td/table/tbody/tr[4]/td[2]/input").get(0);
        passwordInput.setValueAttribute("1234");
        HtmlSubmitInput submit = (HtmlSubmitInput) page.getByXPath("/html/body/table[2]/tbody/tr[3]/td/table/tbody/tr[5]/td/input[1]").get(0);
        return submit.click();
    }

    private void parseNumber() {
        currentPhoneNumber = currentPhoneNumber.replace("-", "");
    }

    private void addPhoneToBook() {
        PhonesStorage ps = new PhonesStorage();
        ps.addPhone(currentPhoneNumber);
    }

    public String getNextPhoneNumber() {
        PhonesStorage ps = new PhonesStorage();
        currentPhoneNumber = ps.getPhone();
        return currentPhoneNumber;
    }

    public boolean needRegistration() {
        return true;
    }

    public String getCurrentPhoneNumber() {
        return currentPhoneNumber;
    }
}
